package com.cgtong.android.fragment;

import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.cgtong.android.R;
import com.cgtong.android.activity.NewsInfoActivity;
import com.cgtong.android.adapter.CityDynamicListAdapter;
import com.cgtong.android.base.BaseTitleFragment;
import com.cgtong.android.bean.NewsBean;
import com.cgtong.android.http.ConstantManager;
import com.cgtong.android.mvp.contract.CityDynamicContract;
import com.cgtong.android.mvp.presenter.CityDynamicPresenter;
import com.cgtong.android.util.PostUtil;
import com.cgtong.android.widget.FastScrollLinearLayoutManager;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.kingja.loadsir.callback.SuccessCallback;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Sky.Bing on 2017/10/17.
 */

public class CityDynamicFragment extends BaseTitleFragment implements CityDynamicContract.View {
    @BindView(R.id.refresh_layout)
    public SwipeRefreshLayout refreshLayout;
    @BindView(R.id.dynamic_list)
    public RecyclerView mDynamicList;

    @BindView(R.id.iv_back_top)
    ImageView mImageViewBackTop;

    private CityDynamicPresenter dynamicPresenter;
    private CityDynamicListAdapter cityDynamicListAdapter;

    @Override
    protected String getContentTitle() {
        return getResources().getString(R.string.bottom_menu_dynamic);
    }

    public static CityDynamicFragment newInstance() {
        return new CityDynamicFragment();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_citydynamic;
    }

    @Override
    public void initData() {
        dynamicPresenter = new CityDynamicPresenter(this);
        initRefreshLayoutAndAdapter();
    }

    @Override
    public void setRefreshing(boolean isRefresh) {
        refreshLayout.setRefreshing(isRefresh);
    }

    @Override
    public void setEnableLoadMore(boolean enabled) {
        cityDynamicListAdapter.setEnableLoadMore(enabled);
    }

    @Override
    public void setRecyclerViewAdapter(final boolean isRefresh, final List<NewsBean> newsBeanList) {
        final int size = newsBeanList == null ? 0 : newsBeanList.size();
        if (size > 0) {
            if (isRefresh) {
                cityDynamicListAdapter.setNewData(newsBeanList);
            } else {
                if (size > 0) {
                    mDynamicList.post(new Runnable() {
                        @Override
                        public void run() {
                            cityDynamicListAdapter.addData(newsBeanList);
                        }
                    });
                }
            }
            mDynamicList.post(new Runnable() {
                @Override
                public void run() {
                    if (size < ConstantManager.HOME_MAX_NEWS) {
                        cityDynamicListAdapter.loadMoreEnd(isRefresh);
                    } else {
                        cityDynamicListAdapter.loadMoreComplete();
                    }
                }
            });
        } else {
            if(!isRefresh){
                onLoadMoreError();
            } else {
                cityDynamicListAdapter.setEmptyView(R.layout.layout_empty, (ViewGroup) mDynamicList.getParent());
            }
        }
        PostUtil.postCallbackDelayed(loadService, SuccessCallback.class);
    }

    @Override
    public void onLoadMoreError() {
        setRefreshing(false);
        mDynamicList.post(new Runnable() {
            @Override
            public void run() {
                cityDynamicListAdapter.loadMoreEnd(false);
            }
        });
    }

    private void initRefreshLayoutAndAdapter() {
        mDynamicList.setLayoutManager(new FastScrollLinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        cityDynamicListAdapter = new CityDynamicListAdapter();
        cityDynamicListAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        mDynamicList.setAdapter(cityDynamicListAdapter);
        mDynamicList.addOnScrollListener(new RecyclerViewScrollListener());
        cityDynamicListAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                String maxTime = cityDynamicListAdapter.getData().get(cityDynamicListAdapter.getData().size() - 1).getPublish_date();
                dynamicPresenter.loadMore(maxTime);
            }
        }, mDynamicList);
        cityDynamicListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                NewsInfoActivity.actionStart(getActivity(), cityDynamicListAdapter.getData().get(i).getId());
            }
        });
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                dynamicPresenter.loadNewsDynamicData("0");
            }
        });
        refreshLayout.setColorSchemeResources(R.color.colorAccent);
        addHeadView();
    }

    private void addHeadView() {
        ImageView headView = (ImageView) LayoutInflater.from(getContext()).inflate(R.layout.adapter_head_view, (ViewGroup) mDynamicList.getParent(), false);
        headView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
        cityDynamicListAdapter.addHeaderView(headView);
    }

    @Override
    protected void loadDataByNet() {
        dynamicPresenter.loadNewsDynamicData("0");
    }

    @Override
    public void onLoadError() {
        setRefreshing(false);
        PostUtil.postCallbackDelayed(loadService, SuccessCallback.class);
        cityDynamicListAdapter.setEmptyView(R.layout.layout_error, (ViewGroup) mDynamicList.getParent());
        cityDynamicListAdapter.setHeaderAndEmpty(true);
    }

    @Override
    protected void onDataReloadByNet(View v) {
    }

    @OnClick(R.id.iv_back_top)
    public void onBackTop(View view) {

//        mDynamicList.smoothScrollToPosition(0);
        mDynamicList.stopScroll();
        LinearLayoutManager mLayoutManager = (LinearLayoutManager) mDynamicList.getLayoutManager();
        mLayoutManager.setSmoothScrollbarEnabled(true);
        int firstVisibilityPosition = mLayoutManager.findFirstVisibleItemPosition();
        if (firstVisibilityPosition > 10) {
            mLayoutManager.scrollToPositionWithOffset(10, 0);
        }
        mDynamicList.smoothScrollToPosition(0);
    }

    /*
     * 滑动监听
     */
    private class RecyclerViewScrollListener extends RecyclerView.OnScrollListener {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
            int firstVisibleItemPosition = manager.findFirstCompletelyVisibleItemPosition();
            // 判断是否滚动超过一屏
            if (firstVisibleItemPosition == 0) {
                mImageViewBackTop.setVisibility(View.INVISIBLE);
            } else {
                mImageViewBackTop.setVisibility(View.VISIBLE);
            }
        }
    }
}